import { LoginForm } from '@/api/auth/login/types'
import { MenuType } from '@/api/auth/menu/types'
import { RouteRecordRaw } from 'vue-router'
import { AdminType } from '../types'

// 引入 views 文件夹下所有 vue 文件
const views = import.meta.glob('@/views/**/*.vue')
const layout = import.meta.glob('@/layout/Layout.vue')

const modules = Object.assign(views, layout)

export const useAdminStore = defineStore(STORE_ADMIN, {
    state: (): AdminType => {
        return {
            admin: {},
            menus: [],
            viewRoutes: [],
            authRoutes: [],
            authButtons: [],
        }
    },
    getters: {},
    actions: {
        // 管理员登录
        async adminUserlogin(loginForm: LoginForm): Promise<boolean> {
            const result = await adminlogin(loginForm)
            if (result.isSuccess) {
                this.admin = result.data
                ElNotification.success({
                    title: '登录成功',
                    message: result.message,
                })
                return true
            }
            ElNotification.error({
                title: '登录失败',
                message: result.message,
            })
            return false
        },
        // 获得菜单权限
        async getAuthRoutes() {
            if (this.admin.id) {
                const result = await getAuthMenus(this.admin.id as number)
                if (!result.isSuccess) return null
                this.menus = result.data.filter((item: any) => item.parentName === null)
                this.authRoutes = this._getChildren(result.data)
                const dynamicRoutes = this.authRoutes.filter((item: RouteRecordRaw) => item.meta?.parentName === null)
                this.viewRoutes = [...constRoutes, ...dynamicRoutes, ...anyRoutes].filter((item: RouteRecordRaw) => item.meta?.isHidden !== true)
            }
        },
        // 将请求到的MenuType数据转化成RouteRecordRaw
        _getChildren(arr: MenuType[]): RouteRecordRaw[] {
            const dynamicRoutes: RouteRecordRaw[] = []
            arr.forEach((item) => {
                let route: RouteRecordRaw = {
                    path: item.path,
                    name: item.name,
                    redirect: item.redirect ?? '',
                    meta: {
                        id: item.id,
                        type: item.type,
                        title: item.title,
                        icon: item.icon,
                        isHidden: item.isHidden,
                        isKeepalive: item.isKeepalive,
                        isAffis: item.isAffis,
                        parentName: item.parentName,
                        componentPath: item.componentPath,
                    },
                }

                if (item.children?.length === 0) {
                    dynamicRoutes.push(route)
                } else {
                    route.children = this._getChildren(item.children)
                    dynamicRoutes.push(route)
                }
            })
            return getFlatArray(dynamicRoutes, false)
        },
        // 初始化权限路由
        initAuthRoute() {
            // 存在权限路由，则添加
            if (this.authRoutes.length !== 0) {
                this.authRoutes.forEach((route: RouteRecordRaw) => {
                    route.component = route.meta?.componentPath ? modules[route.meta?.componentPath] : undefined
                    const parentName = route.meta?.parentName
                    parentName ? router.addRoute(parentName, route) : router.addRoute(route)
                })
            }
            // 添加任意路由
            anyRoutes.forEach((route: RouteRecordRaw) => {
                router.addRoute(route)
            })
        },
        // 获得按钮权限
        async getAuthButtonPermissions() {
            if (this.admin.id) {
                const result = await getAuthButtonPermissions(this.admin.id)
                if (!result.isSuccess) return
                this.authButtons = result.data
            }
        },
        // 刷新toekn后设置toekn
        setToken(accessToken: string) {
            this.admin.accessToken = accessToken
        },
        // 获取用户信息
        async getAdminUserInfo(): Promise<boolean> {
            const result = await getAdminUserInfo()
            if (!result.isSuccess) return false
            this.admin = Object.assign(result.data, { accessToken: this.admin.accessToken, refreshToken: this.admin.refreshToken })
            return true
        },
        // 退出登录
        adminUserLogout() {
            this.admin = {}
            this.authRoutes = []
            this.authButtons = []
            this.viewRoutes = []
        },
    },
    persist: true,
})
